<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>闭包的应用 防抖 节流</title>
    <style>

    </style>
</head>

<body>
    <div style="display: flex;align-items: flex-start;">
        <!-- 防抖：一直点击总是成功不了，直到停止才会开始触发操作 -->
        <!--应用： 1、输入框搜索延迟发送请求 2、防止用户重复点击按钮 3、窗口大小调整，调整事件触发频率，防止页面抖动 -->
        <button id="btn1">点击防抖</button>
        <!-- 节流：一直点击，会在一定周期内执行，可以控制执行频率 -->
        <!-- 应用：1、页面滚动加载 2、防止用户频繁点击 -->
        <button id="btn2">点击节流</button>

        <div id="dom1"></div>
    </div>
</body>
<script>
    let btn2 = document.getElementById('btn2')
    btn2.addEventListener('click', throttle(send, 1000))
    function send() {
        console.log(this, '节流');
    }

    function throttle(send, timeout) {
        let oldTime = Date.now()

        return function () {
            let that = this
            let args = arguments
            if (Date.now() - oldTime > timeout) {
                send.call(that, ...args)
                oldTime = Date.now()
            }
        }
    }
</script>
<script>
    let btn = document.getElementById('btn1')
    btn.addEventListener('click', debounce(send, 1000))

    function send() {
        console.log('防抖', this);
    }
    function debounce(send, timeout) {
        let timer

        return function () {
            let _this = this
            let arg = arguments
            if (timer) clearTimeout(timer)
            timer = setTimeout(() => {
                send.call(_this, ...arg)
            }, timeout);
        }
    }
</script>

</html>